<script setup lang="ts">
import type { FormRules, FormProps } from 'naive-ui'
import type { IFormItem } from '@/components/NFormBuilder/types.d.ts'
import { ScConstants } from '@/components/NFormBuilder/unit/ScConstants'
import NFormBuilder from '@/components/NFormBuilder/index.vue'
import DiuInput from './DiyInput.vue'
const queryForm = ref({
  sex: null,
})
const stateOptions = reactive({
  sexOptions: [],
})
const options = [
  {
    label: '男',
    value: 1,
  },
  {
    label: '女',
    value: 2,
  },
]
const getOptions = () => {
  // 模拟异步获取数据
  setTimeout(() => {
    stateOptions.sexOptions = options
  }, 1000)
}
getOptions()

const sc = new ScConstants(12)
const formItems = ref<IFormItem[]>([
  sc.input('输入框', 'name'),
  sc.number('数值输入框', 'age'),
  sc.select('下拉框', 'sex', {
    options: options,
  }),
  {
    ...sc.select('动态值下拉框', 'sexTwo', {
      options: computed(() => stateOptions.sexOptions),
    }),
    hidden: () => queryForm.value.sex === 1,
  },
  sc.date('日期组件', 'date.one'),
  sc.dateFormat('格式化', 'date.two'),
  sc.date('单字段范围', 'date.three', {
    type: 'daterange',
  }),
  sc.date('多字段', ['date.starTime', 'date.endTime'], {
    type: 'daterange',
  }),
  sc.radio('单选', 'radio', { options }),
  sc.checkbox('单选', 'checkbox', { options }),
  sc.image('图片', 'avatar'),
  {
    ...sc.imageList('图片列表', 'avatar'),
    span: 24,
  },
  {
    ...sc.rich('富文本', 'content'),
    span: 24,
  },
  sc.input('插槽测试', 'slot_text'),
  sc.input('key和自定义相同', 'custom'),
  {
    ...sc.other('自定义组件', 'custom', DiuInput),
  },
])
const rules: FormRules = {
  name: [
    {
      required: true,
      message: '部门名称不能为空',
      trigger: 'blur',
    },
  ],
}
const formConfig: FormProps = {
  labelPlacement: 'left',
  labelWidth: '140px',
  requireMarkPlacement: 'left',
}
const ruleForm = ref()
const handSubmit = async () => {
  try {
    await ruleForm.value.validate()
    msgUtil.$message.success('验证通过')
  } catch (e) {
    msgUtil.$message.error(e[0][0].message)
  }
}
</script>

<template>
  <div class="form-test">
    <n-form-builder
      ref="ruleForm"
      :formConfig="formConfig"
      v-model="queryForm"
      :form-items="formItems"
      :rules="rules"
    >
      <template #slot_text>
        <div class="text-orange-500">我是插槽会完整替换掉组件做展示可以使用我</div>
      </template>
    </n-form-builder>
    <div class="tools flex items-center justify-center mt-20 mb-20">
      <n-space>
        <n-button type="primary" @click="handSubmit">提交</n-button>
      </n-space>
    </div>
  </div>
</template>

<style scoped lang="scss">
.form-test {
  background: #fff;
}
</style>
